#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
将Markdown文档转换为DOCX格式的脚本
需要安装: pip install python-docx markdown
"""

import markdown
from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
import re
import os

def markdown_to_docx(md_file, docx_file):
    """将Markdown文件转换为DOCX文件"""
    
    # 读取Markdown文件
    with open(md_file, 'r', encoding='utf-8') as f:
        md_content = f.read()
    
    # 创建Word文档
    doc = Document()
    
    # 设置文档样式
    style = doc.styles['Normal']
    font = style.font
    font.name = '微软雅黑'
    font.size = Pt(12)
    
    # 处理Markdown内容
    lines = md_content.split('\n')
    
    for line in lines:
        line = line.strip()
        
        if not line:
            # 空行
            doc.add_paragraph()
            continue
            
        # 处理标题
        if line.startswith('#'):
            level = len(line) - len(line.lstrip('#'))
            title_text = line.lstrip('#').strip()
            
            if level == 1:
                # 一级标题
                heading = doc.add_heading(title_text, level=1)
                heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
            elif level == 2:
                # 二级标题
                doc.add_heading(title_text, level=2)
            elif level == 3:
                # 三级标题
                doc.add_heading(title_text, level=3)
            elif level == 4:
                # 四级标题
                doc.add_heading(title_text, level=4)
            else:
                # 五级及以下标题
                p = doc.add_paragraph()
                run = p.add_run(title_text)
                run.bold = True
                run.font.size = Pt(14)
        
        # 处理表格
        elif line.startswith('|'):
            # 收集表格行
            table_lines = [line]
            continue
            
        # 处理列表
        elif line.startswith('- ') or line.startswith('* '):
            list_text = line[2:].strip()
            # 处理粗体
            list_text = re.sub(r'\*\*(.*?)\*\*', r'\1', list_text)
            p = doc.add_paragraph(list_text, style='List Bullet')
            
        # 处理普通段落
        else:
            # 处理粗体文本
            if '**' in line:
                p = doc.add_paragraph()
                parts = re.split(r'(\*\*.*?\*\*)', line)
                for part in parts:
                    if part.startswith('**') and part.endswith('**'):
                        # 粗体文本
                        run = p.add_run(part[2:-2])
                        run.bold = True
                    else:
                        # 普通文本
                        p.add_run(part)
            else:
                doc.add_paragraph(line)
    
    # 处理表格（简化处理）
    table_content = []
    in_table = False
    
    for line in md_content.split('\n'):
        if '|' in line and not line.strip().startswith('#'):
            if not in_table:
                in_table = True
                table_content = []
            
            # 清理表格行
            row = [cell.strip() for cell in line.split('|') if cell.strip()]
            if row and not all(cell.startswith('-') for cell in row):
                table_content.append(row)
        else:
            if in_table and table_content:
                # 创建表格
                if len(table_content) > 1:
                    table = doc.add_table(rows=len(table_content), cols=len(table_content[0]))
                    table.style = 'Table Grid'
                    
                    for i, row_data in enumerate(table_content):
                        for j, cell_data in enumerate(row_data):
                            if j < len(table.rows[i].cells):
                                cell = table.rows[i].cells[j]
                                cell.text = cell_data
                                # 表头加粗
                                if i == 0:
                                    for paragraph in cell.paragraphs:
                                        for run in paragraph.runs:
                                            run.bold = True
                
                table_content = []
                in_table = False
    
    # 保存文档
    doc.save(docx_file)
    print(f"文档已成功转换并保存为: {docx_file}")

if __name__ == "__main__":
    # 转换文档
    md_file = "项目分析报告.md"
    docx_file = "索奇智慧文旅数据大屏项目分析报告.docx"
    
    if os.path.exists(md_file):
        markdown_to_docx(md_file, docx_file)
    else:
        print(f"找不到文件: {md_file}")